package com.lanou3g.springcloud.calc.consumer.web;

import com.lanou3g.springcloud.calc.consumer.bean.CalcResult;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

@Controller
public class CalcController {

	@Autowired
	private RestTemplate restTemplate;

	@HystrixCommand(fallbackMethod = "calcFallback")
	@RequestMapping("/calc")
	public String calc(CalcResult calcParam, Model model) {

		Integer numA = calcParam.getNumA();
		Integer numB = calcParam.getNumB();
		Integer operator = Integer.parseInt(calcParam.getOperator());

		String url = "http://calc-provider/calc/"+numA+"/"+numB+"/"+operator;
		CalcResult result = restTemplate.getForObject(url, CalcResult.class);
		model.addAttribute("obj", result);
		return "index";
	}

	public String calcFallback(CalcResult calcParam, Model model) {
		calcParam.setResult(calcParam.getNumA() + calcParam.getNumB());
		model.addAttribute("obj", calcParam);
		return "index";
	}
}
